<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class loai_model extends CI_Model
{
	public function __construct()
	{
		parent::__construct();
		$this->load->library("unicode");
	}
	public function getDDL($idCL="",$idLP="")
	{
		if(is_numeric($idCL)&&is_numeric($idLP))
		$query = $this->db->query("SELECT id, ten, tenUrl FROM loai WHERE anhien = 1 AND idCL = ? AND idLP = ? ORDER BY thutu",array($idCL, $idLP));
		else $query = $this->db->query("SELECT id, ten, tenUrl FROM loai WHERE anhien = 1 ORDER BY thutu");
		return $query->result();
	}
	public function select()
	{
		$query = $this->db->query("SELECT loai.id, chungloai.ten AS tenCL, loaiphong.ten AS tenLP, loai.ten, loai.thutu, loai.anhien FROM loaiphong, chungloai, loai WHERE loai.idLP = loaiphong.id AND loai.idCL = chungloai.id ORDER BY loai.thutu");
		return $query->result();
	}
	public function edit($id)
	{
		$query = $this->db->query("SELECT * FROM loai WHERE id = ?",array($id));
		return $query->result();
	}
	public function insert($idCL, $idLP, $ten, $thutu)
	{
		$tenUrl = $this->unicode->change($ten);
		if(is_numeric($thutu)) settype($thutu,"int"); else $thutu = 0;
		if(is_numeric($idCL)&&is_numeric($idLP))
		{
			$this->db->query("INSERT INTO loai VALUES (NULL, ?, ?, ?, ?, ?, 1)", array($idCL, $idLP, $ten, $tenUrl, $thutu));
			return $this->db->insert_id();
		} else return 0;
	}
	public function update($id, $idCL, $idLP, $ten, $thutu, $anhien)
	{
		$tenUrl = $this->unicode->change($ten);
		if(is_numeric($id)&&is_numeric($idCL)&&is_numeric($idLP))
		{
		$query = $this->db->query("UPDATE loai SET idCL = ?, idLP = ?, ten = ?, tenUrl = ?, thutu = ?, anhien = ? WHERE id = ?", array($idCL, $idLP, $ten, $tenUrl, $thutu, $anhien, $id));
		$chk = $this->db->query("SELECT id FROM loai WHERE idCL = ? AND idLP = ? AND ten = ? AND tenUrl = ? AND thutu = ? AND anhien = ? AND id = ?", array($idCL, $idLP, $ten, $tenUrl, $thutu, $anhien, $id));
		if($chk->num_rows() > 0) return TRUE;
		} return FALSE;
	}
	public function delete($id)
	{
		$this->db->query("DELETE FROM loai WHERE id = ?",array($id));
		$query = $this->db->query("SELECT id FROM loai WHERE id = ?",array($id));
		if($query->num_rows()>0) return FALSE; return TRUE;
	}
}